import { defineStore } from "pinia";
import { getToken, removeToken, setToken } from "../utils/token-utils";
import type { UserInfoState } from "./interface";
import { staticRoutes, allAsyncRoutes, anyRoutes } from "@/router/routes";
import {
  loginApi,
  getUserInfoApi,
  // getRoutesApi
} from "@/api/user";
import type { RouteRecordRaw } from "vue-router";
import router from "@/router";
import cloneDeep from "lodash/cloneDeep";

/**
 * 过滤动态路由表，只保留拥有访问权限的路由
 * @param allAsyncRoutes 动态路由表
 * @param routes 用户路由权限
 * @returns 过滤动态路由表
 */
const filterAllAsyncRoutes = (
  allAsyncRoutes: RouteRecordRaw[],
  routes: string[]
) => {
  return allAsyncRoutes.filter((route) => {
    if (routes.includes(route.name as string)) {
      if (route.children && route.children.length) {
        const childRoutes = filterAllAsyncRoutes(route.children, routes);
        route.children = childRoutes;
      }
      return true;
    }
    return false;
  });
};

/**
 * 追加路由配置方法
 * @param routes 路由配置
 */
const addRoutes = (routes: RouteRecordRaw[]) => {
  routes.forEach((route) => {
    router.addRoute(route);
  });
};

// 动态导入所有动态组件
// const modules = import.meta.glob(["@/views/**/*.vue", "@/layout/**/*.vue"]);
// /*
//   "@/layout/index.vue" --> /src/layout/index.vue
//   "@/views/product/trademark/index.vue" --> /src/views/product/trademark/index.vue
// */
// const addComponents = (routes) => {
//   routes.forEach((route) => {
//     const componentPath = route.component.replace("@", "/src");
//     route.component = modules[componentPath];
//     if (route.children && route.children.length) {
//       addComponents(route.children);
//     }
//   });
// };

/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */
export const useUserInfoStore = defineStore("userInfo", {
  state: (): UserInfoState => ({
    token: getToken() as string,
    name: "",
    avatar: "",
    menuRoutes: [], // 路由配置项（将来会渲染成左侧菜单）
    routes: [], // 路由权限列表
    buttons: [], // 按钮权限列表
  }),

  actions: {
    async login(username: string, password: string) {
      const res = await loginApi(username, password);
      this.token = res.token; // 存在pinia
      setToken(res.token); // 存在localStorage
    },

    // 后台实现方案
    // async getInfo() {
    //   const [res, routes] = await Promise.all([
    //     getUserInfoApi(),
    //     getRoutesApi(),
    //   ]);

    //   this.routes = routes;
    //   this.buttons = res.buttons;
    //   this.name = res.name;
    //   this.avatar = res.avatar;

    //   // 将后端返回动态路由表中component转化为真正的组件
    //   addComponents(routes);
    //   // 将路由追加到路由表中，让其生效
    //   addRoutes([...routes, ...anyRoutes]);

    //   this.menuRoutes = [...staticRoutes, ...routes];
    // },

    // 前台实现方案
    async getInfo() {
      const res = await getUserInfoApi();
      this.routes = res.routes;
      this.buttons = res.buttons;
      this.name = res.name;
      this.avatar = res.avatar;
      // 对所有动态路由表进行过滤，只保留用户拥有访问权限的路由
      const filterRoutes = filterAllAsyncRoutes(
        cloneDeep(allAsyncRoutes),
        res.routes
      );
      // 给vue-router添加路由配置，此时用户就能输入网址访问
      addRoutes([...filterRoutes, ...anyRoutes]);
      // 给左侧菜单添加配置
      this.menuRoutes = [...staticRoutes, ...filterRoutes];
    },

    reset() {
      // 删除localStorage中保存的token
      removeToken();
      // 提交重置用户信息的mutation
      this.token = "";
      this.routes = [];
      this.buttons = [];
      this.name = "";
      this.avatar = "";
    },
  },
});
